/*
 * ******************************************************************************
 *   Copyright (c) 2014 Gabriele Mariotti.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *  *****************************************************************************
 */

package it.gmariotti.cardslib.library.view.listener;


import it.gmariotti.cardslib.library.AnimatorListenerAdapter;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.VelocityDetector;
import ohos.multimodalinput.event.TouchEvent;

import static ohos.multimodalinput.event.TouchEvent.*;

/**
 * A {@link } that makes any {@link Component} dismissable when the
 * user swipes (drags her finger) horizontally across the view.
 *
 * <p><em>For {@link } list items that don't manage their own touch events
 * (i.e. you're using
 * {@link }
 * or an equivalent listener on {@link } or
 * {@link }, use {@link } instead.</em></p>
 *
 * <p>Example usage:</p>
 *
 * <pre>
 * view.setOnTouchListener(new SwipeDismissTouchListener(
 *         view,
 *         null, // Optional token/cookie object
 *         new SwipeDismissTouchListener.OnDismissCallback() {
 *             public void onDismiss(View view, Object token) {
 *                 parent.removeView(view);
 *             }
 *         }));
 * </pre>
 *
 * <p>This class Requires API level 12 or later due to use of {@link}.</p>
 *
 * @see SwipeDismissListViewTouchListener
 */
public class SwipeDismissTopBottomTouchListener implements Component.TouchEventListener {

    // Cached ViewConfiguration and system-wide constant values
    private int mSlop;
    private int mMinFlingVelocity;
    private int mMaxFlingVelocity;
    private long mAnimationTime;

    // Fixed properties
    private Component mView;
    private DismissCallbacks mCallbacks;
    private int mViewHeight = 1; // 1 and not 0 to prevent dividing by zero

    // Transient properties
    private float mDownX;
    private float mDownY;
    private boolean mSwiping;
    private int mSwipingSlop;
    private Object mToken;
    private VelocityDetector mVelocityTracker;
    private float mTranslationY;
    private float mOriginalY;


    /**
     * The callback interface used by {@link SwipeDismissTopBottomTouchListener} to inform its client
     * about a successful dismissal of the view for which it was created.
     */
    public interface DismissCallbacks {
        /**
         * Called to determine whether the view can be dismissed.
         * @param token
         * @return boolean
         */
        boolean canDismiss(Object token);

        /**
         * Called when the user has indicated they she would like to dismiss the view.
         *
         * @param view  The originating {@link Component} to be dismissed.
         * @param token The optional token passed to this object's constructor.
         */
        void onDismiss(Component view, Object token);
    }

    /**
     * Constructs a new swipe-to-dismiss touch listener for the given view.
     *
     * @param view      The view to make dismissable.
     * @param token     An optional token/cookie object to be passed through to the callback.
     * @param callbacks The callback to trigger when the user has indicated that she would like to
     *                  dismiss this view.
     */
    public SwipeDismissTopBottomTouchListener(Component view, Object token, DismissCallbacks callbacks) {
        mSlop = 8;
        mMinFlingVelocity = 50 * 16;
        mMaxFlingVelocity = 8000;
        mAnimationTime = 200;
        mView = view;
        mToken = token;
        mCallbacks = callbacks;
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        // offset because the view is translated during swipe

        touchEvent.setScreenOffset(0, mTranslationY);

        if (mViewHeight < 2) {
            mViewHeight = mView.getHeight();
        }

        if (mOriginalY == 0) {
            mOriginalY = mView.getContentPositionY();
        }

        switch (touchEvent.getAction()) {
            case PRIMARY_POINT_DOWN: {
                // TODO: ensure this is a finger, and set a flag
                mDownX = touchEvent.getPointerScreenPosition(0).getX();
                mDownY = touchEvent.getPointerScreenPosition(0).getY();
                if (mCallbacks.canDismiss(mToken)) {
                    mVelocityTracker = VelocityDetector.obtainInstance();
                    mVelocityTracker.addEvent(touchEvent);
                }
                //todo no such method
//                view.onTouchEvent(motionEvent);
                return true;
            }

            case TouchEvent.PRIMARY_POINT_UP: {
                if (mVelocityTracker == null) {
                    break;
                }

                float deltaY = touchEvent.getPointerScreenPosition(0).getY() - mDownY;
                mVelocityTracker.addEvent(touchEvent);
                mVelocityTracker.calculateCurrentVelocity(1000);
                float velocityX = mVelocityTracker.getHorizontalVelocity();
                float absVelocityX = Math.abs(velocityX);
                float absVelocityY = Math.abs(mVelocityTracker.getVerticalVelocity());
                boolean dismiss = false;
                boolean dismissRight = false;
                if (Math.abs(deltaY) > 2 * mViewHeight / 3 && mSwiping) {
                    dismiss = true;
                    dismissRight = deltaY > 0;
                } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
                        && absVelocityY < absVelocityX
                        && mSwiping) {
                    // dismiss only if flinging in the same direction as dragging
                    dismiss = (velocityX < 0) == (deltaY < 0);
                    dismissRight = mVelocityTracker.getHorizontalVelocity() > 0;
                }
                if (dismiss) {
                    // dismiss

                    AnimatorProperty animatorProperty = mView.createAnimatorProperty();
                    animatorProperty.moveFromX(mView.getLeft()).moveToX(dismissRight ? mViewHeight : -mViewHeight).alpha(0).setDuration(mAnimationTime)
                            .setStateChangedListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onEnd(Animator animator) {
                                    performDismiss();
                                }
                            });
                } else if (mSwiping) {
                    // cancel
                    AnimatorProperty animatorProperty = mView.createAnimatorProperty();
                    animatorProperty.moveFromX(mView.getLeft()).moveToX(0).alpha(1).setDuration(mAnimationTime);
                }
                mVelocityTracker.clear();
                mVelocityTracker = null;
                mTranslationY = 0;
                mDownX = 0;
                mDownY = 0;
                mSwiping = false;
                break;
            }

            case CANCEL: {
                if (mVelocityTracker == null) {
                    break;
                }

                AnimatorProperty animatorProperty = mView.createAnimatorProperty();
                animatorProperty.moveFromX(mView.getLeft()).moveToX(0).alpha(1).setDuration(mAnimationTime);
                mVelocityTracker.clear();
                mVelocityTracker = null;
                mTranslationY = 0;
                mDownX = 0;
                mDownY = 0;
                mSwiping = false;
                break;
            }

            case POINT_MOVE: {
                if (mVelocityTracker == null) {
                    break;
                }

                mVelocityTracker.addEvent(touchEvent);
                float deltaX = touchEvent.getPointerScreenPosition(0).getX() - mDownX;
                float deltaY = touchEvent.getPointerScreenPosition(0).getY() - mDownY;
                if (Math.abs(deltaY) > mSlop && Math.abs(deltaX) < Math.abs(deltaY) / 2 & deltaY > 0) {
                    mSwiping = true;
                    mSwipingSlop = (deltaY > 0 ? mSlop : 0);
                    mView.getComponentParent().moveChildToFront(mView);

                    //todo no such method
                    // Cancel listview's touch
//                    MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
//                    cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
//                            (motionEvent.getActionIndex() <<
//                                    MotionEvent.ACTION_POINTER_INDEX_SHIFT));
//                    mView.onTouchEvent(cancelEvent);
//                    cancelEvent.recycle();
                }

                if (mSwiping) {
                    mTranslationY = deltaY >= 0 ? deltaY : 0;
                    mView.setTranslationY(deltaY >= 0 ? deltaY - mSwipingSlop : 0);
                    // TODO: use an ease-out interpolator or such
                    mView.setAlpha(deltaY >= 0 ? Math.max(0f, Math.min(1f,
                            1f - 1.5f * Math.abs(deltaY) / mViewHeight)) : 1f);
                    return true;
                }
                break;
            }
        }
        return false;
    }

    private void performDismiss() {
        // Animate the dismissed view to zero-height and then fire the dismiss callback.
        // This triggers layout on each animation frame; in the future we may want to do something
        // smarter and more performant.

        final ComponentContainer.LayoutConfig lp = mView.getLayoutConfig();
        final int originalHeight = mView.getHeight();
        AnimatorValue animatorValue = new AnimatorValue();
        animatorValue.setStateChangedListener(new AnimatorListenerAdapter() {
            @Override
            public void onEnd(Animator animator) {
                mCallbacks.onDismiss(mView, mToken);
                // Reset view presentation
                mView.setAlpha(1f);
                mView.setTranslationX(0);
                lp.height = originalHeight;
                mView.setLayoutConfig(lp);
            }
        });
        animatorValue.setValueUpdateListener((animatorValue1, v) -> {
            lp.height = (int) (originalHeight - (originalHeight - 1) * v);
            mView.setLayoutConfig(lp);

        });
        animatorValue.setDuration(mAnimationTime);
        animatorValue.start();
    }
}